import { reactive } from "vue";
import { defineStore } from "pinia";
//引入用户中心数据类型
import type { MemberCenter } from "./types/type";
//引入路由类型
import { RouteLocationNormalized, RouteRecordRaw } from "vue-router";

//自定义类型仓库 state也需要const
export const useMemberCenter = defineStore("memberCenter", () => {
  const state: MemberCenter = reactive({
    // 是否开启会员中心
    open: false,
    // 用户中心布局模式
    layoutMode: "Default",
    // 当前激活菜单
    activeRoute: null,
    // 从后台加载到的菜单
    viewRoutes: [],
    // 是否显示一级菜单标题(当有多个一级菜单分组时显示)
    showHeadline: false,
    // 权限节点
    authNode: new Map(),
    // 收缩布局
    shrink: false,
    // 菜单展开（小屏设备）
    menuExpand: false,
  });

  //保存权限节点
  const setAuthNode = (key: string, data: string[]) => {
    state.authNode.set(key, data);
  };
  //当前激活菜单确定
  const setActiveRoute = (route: RouteLocationNormalized | RouteRecordRaw) => {
    state.activeRoute = route;
  };
  //菜单是否展开
  const toggleMenuExpand = (expand = !state.menuExpand) => {
    state.menuExpand = expand;
  };
  // 是否显示一级菜单标题
  const setShowHeadline = (show: boolean): void => {
    state.showHeadline = show;
  };
  //用户中心从后台加载到的菜单
  const setViewRoutes = (data: RouteRecordRaw[]): void => {
    state.viewRoutes = encodeRoutesURI(data);
  };
  return {
    state,
    setAuthNode,
    setActiveRoute,
    toggleMenuExpand,
    setShowHeadline,
    setViewRoutes,
  };
});

function encodeRoutesURI(data: RouteRecordRaw[]) {
  data.forEach((item) => {
    /**
     * 判断后端返回的菜单路由数据有没有iframe类型的
     * iframe类型:
     *  引入其他网页内容到项目中的标签
     *  https://www.jianshu.com/p/22bc6e287a64 学习链接
     */
    if (item.meta?.type == "iframe") {
      item.path = "/user/iframe/" + encodeURIComponent(item.path);
    }

    if (item.children && item.children.length) {
      item.children = encodeRoutesURI(item.children);
    }
  });
  return data;
}
